package com.byzoro.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
public class Upload {
    public final static String rootPath = System.getProperty("user.dir");
    public final static String staticPath = File.separator + "upload" + File.separator + "head_pic" + File.separator;
    public final static String mapPath = "img/head_pic/";
    public final static String staticMusicPath = File.separator + "upload" + File.separator + "music" + File.separator;
    public final static String mapMusicPath = "music/model/";

    public static JsonResult upload(MultipartFile file, String type) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传失败，请选择文件");
        }

        String fileName;
        String filePath;
        String relative;
        switch (type) {
            case "music" -> {
                fileName = file.getOriginalFilename();
                filePath = rootPath + staticMusicPath;
                relative = File.separator + mapMusicPath + fileName;
            }
            default -> {
                fileName = System.currentTimeMillis() + file.getOriginalFilename();
                filePath = rootPath + staticPath;
                relative = File.separator + mapPath + fileName;
            }
        }

        File dest = new File(filePath + fileName);

        try {
            if (!dest.getParentFile().exists()) {
                boolean mkdirs = dest.getParentFile().mkdirs();
                if (!mkdirs) {
                    log.error("make dir fail: {}", dest.toString());
                    return JsonResult.fail("上传路径创建失败");
                }
            }
            file.transferTo(dest);
            return JsonResult.success("上传成功", relative);
        } catch (IOException e) {
            log.error("upload user header picture fail: ", e);
            return JsonResult.fail("上传失败");
        }
    }
}
